// middleware/middleware_log.go
package middleware

import (
	"bytes"
	"muziai-server/service/common"

	"github.com/gin-gonic/gin"
	"io"
)

type responseWriter struct {
	gin.ResponseWriter
	data *bytes.Buffer
}

func (r *responseWriter) Write(b []byte) (int, error) {
	r.data.Write(b)
	return r.ResponseWriter.Write(b)
}

func MiddlewareLog(c *gin.Context) {
	log := common.NewLogByGin(c)
	method := c.Request.Method
	if method != "GET" {
		// 如果是文件上传的
		byteData, err := io.ReadAll(c.Request.Body)
		if err == nil {
			c.Request.Body = io.NopCloser(bytes.NewReader(byteData))
		}
		log.SetRequest(byteData)
	}

	rw := responseWriter{
		ResponseWriter: c.Writer,
		data:           bytes.NewBuffer([]byte("")),
	}
	c.Writer = &rw
	c.Set("log", log)
	c.Next()
	_logShow, ok := c.Get("logShow")
	if !ok {
		return
	}
	logShow, _ := _logShow.(bool)
	if !logShow {
		return
	}
	log.SetResponse(rw.data.Bytes())
	log.Save()
}
